<?php
// inc/class/template.php
namespace smp;

use smp\Base;

class Template extends Base {

	// ClassProperties ->
	protected static $errno, $error, $trace, $errorpage;
	protected static $readonly = array('error', 'errno', 'trace', 'readonly', 'secret');
	protected static $secret = array('readonly', 'secret');

	// prepare ->
	public static function prepare($path, $legacy = false) {
		static::setTrace('prepare');
		if(empty($path) or !is_string($path)) {
			static::$errno = 0;
			static::$error = 'Argument 1 has to be a string!';
			static::$errorpage = 'err.template.prepare.htm';
		return false;
		}
		if(!is_bool($legacy)) {
			static::$errno = 0;
			static::$error = 'Argument 2 has to be bool!';
			static::$errorpage = 'err.template.prepare.htm';
		return false;
		}

		// Legacy ->
		if($legacy) {
			$ret = join(file(_base.$path));
			unset($path, $legacy);
		return $ret;
		}

	return NULL;
	}

	// process ->
	public static function process($content, $template = NULL, $legacy = false) {
		static::setTrace('process');
		if(empty($content) or !is_array($content)) {
			static::$errno = 0;
			static::$error = 'Argument 1 has to be an array!';
			static::$errorpage = 'err.template.process.htm';
		return false;
		}
		if(!is_bool($legacy)) {
			static::$errno = 0;
			static::$error = 'Argument 3 has to be bool!';
			static::$errorpage = 'err.template.process.htm';
		return false;
		}
		if($legacy and !is_string($template)) {
			static::$errno = 0;
			static::$error = 'Argument 2 has to be a string!';
			static::$errorpage = 'err.template.process.htm';
		return false;
		}

		// Legacy ->
		if($legacy) {
			foreach($content as $k => $v) {
				$template = preg_replace('/\{'.$k.'\}/Usi', $v, $template);
				unset($k, $v);
			}
			$template = preg_replace('/\{*\}/Usi', '', $template);
			unset($content, $legacy);
		return $template;
		}

	return NULL;
	}

	public static function flush($template = NULL, $legacy = false) {
		static::setTrace('flush');
		if(!is_bool($legacy)) {
			static::$errno = 0;
			static::$error = 'Argument 2 has to be bool!';
			static::$errorpage = 'err.template.flush.htm';
		return false;
		}
		if($legacy and !is_string($template)) {
			static::$errno = 0;
			static::$error = 'Argument 1 has to be a string!';
			static::$errorpage = 'err.template.flush.htm';
		return false;
		}

		// Legacy ->
		if($legacy and !empty($template)) {
			echo $template;
		return;
		}

	return NULL;
	}
}

?>